package com.hy.service.impl;

import com.hy.bean.*;
import com.hy.dao.BuytableDao;
import com.hy.dao.impl.BuytableDaoImpl;
import com.hy.service.BuytableService;
import com.hy.utils.DBManager;
import com.hy.utils.DateUtils;
import org.apache.commons.dbutils.DbUtils;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Service
public class BuytableServiceImpl implements BuytableService {

    BuytableDao buytableDao = new BuytableDaoImpl();

    @Override
    public List<Map<String,Object>> queryAllByLimit(String state,Integer page, Integer limit) throws Exception {

        return buytableDao.queryAllByLimit(state,page,limit);
    }

    @Override
    public List<Map<String, Object>> queryAllStatis(String buyNumber,String buyer, String producername, String buyTime, String reachTime, Integer page, Integer limit) throws Exception {
        return buytableDao.queryAllStatis(buyNumber,buyer,producername,buyTime,reachTime,page,limit);
    }

    @Override
    public long countStatis(String buyNumber,String buyer, String producername, String buyTime, String reachTime) throws Exception {
        return buytableDao.countStatis(buyNumber,buyer,producername,buyTime,reachTime);
    }

    @Override
    public boolean updateState(Integer id,String state,Integer userId) throws Exception {
        Connection connection = null;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);

            boolean update = buytableDao.updateState(id,state,connection);
            boolean i = buytableDao.updateUser(id,userId,DateUtils.getNowTime(),userId, DateUtils.getNowTime(),connection);
            if (update == true && i == true) {
                connection.commit();
                return true;
            }
            return false;
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public boolean updateInfo(Integer id,Integer userId ,String Info) throws Exception {
        Connection connection = null;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);

            boolean update = buytableDao.updateInfo(id,Info,connection);
            boolean i = buytableDao.updateUser(id,userId,DateUtils.getNowTime(),userId, DateUtils.getNowTime(),connection);
            if (update == true && i == true) {
                connection.commit();
                return true;
            }
            return false;
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }


    @Override
    public long count(String state) throws Exception {
        return buytableDao.count(state);
    }

    @Override
    public long countDetails(String state,String status,Integer id) throws Exception {
        return buytableDao.countDetails(state,status,id);
    }

    @Override
    public List<Map<String, Object>> queryAllDetails(String state,String status,Integer id, Integer page, Integer limit) throws Exception {
        return buytableDao.queryAllDetails(state,status,id,page,limit);
    }

    @Override
    public List<Producertable> queryAllVendor() throws Exception {
        return buytableDao.queryAllVendor();
    }

    @Override
    public long countCar(String name) throws Exception {
        return buytableDao.countCar(name);
    }

    @Override
    public boolean add(Map<String, Object> map) throws Exception {
        Connection connection = null;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);
            Carpartstable car = new Carpartstable();
            BuyParttable buyParttable = new BuyParttable();
            car.setPartname(map.get("partName").toString());
            car.setCostprice(Double.parseDouble((String) map.get("costPrice")));
            car.setProducertableId((Integer) map.get("producerTable_id"));
            car.setPartunit(map.get("partUnit").toString());
            car.setPartcode(map.get("partCode").toString());
            car.setPartcubage(Integer.parseInt((String) map.get("partCubage")));
            car.setPartweight(Double.parseDouble((String) map.get("partWeight")));
            car.setPartstore(Integer.parseInt((String) map.get("partStore")));
            car.setPartminstore(Integer.parseInt((String) map.get("partMinStore")));
            car.setSaleprice(Double.parseDouble((String) map.get("salePrice")));
            car.setRebate(Double.parseDouble((String) map.get("rebate")));
            car.setDetails(map.get("details").toString());
            car.setPartcreater((String) map.get("userId"));
            int l = buytableDao.insertCar(car, connection);
            buyParttable.setBuycount(Integer.parseInt((String) map.get("buyCount")));
            buyParttable.setFactoryrebate(Double.parseDouble((String) map.get("rebate")));
            buyParttable.setBuytableId((Integer) map.get("id"));
            buyParttable.setParttableId(l);
            Object totalPriceObj = map.get("totalPrice");
            double totalPrice = 0.0;
            if (totalPriceObj instanceof Number) {
                totalPrice = ((Number) totalPriceObj).doubleValue();
                buyParttable.setTotalprice(totalPrice);
            }
            int i = buytableDao.insertBuyPart(buyParttable, connection);
            if (l>0&&i>0) {
                connection.commit();
                return true;
            }
            return false;
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public boolean update( Integer lid,Integer cid, Double costPrice, Integer buyCount, Double totalPrice,String partDetailChanger) {
        Connection connection = null;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);

            int update = buytableDao.updateBuy(connection,totalPrice,cid,buyCount);
            int i = buytableDao.updateCar(connection,costPrice,lid,partDetailChanger);
            if (update >0 && i >0) {
                connection.commit();
                return true;
            }
            return false;
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public int updateCode(int cid,String code, Integer id, String name) throws Exception {
        Connection connection = DBManager.getConnection();
        //更新总金额
        int i1 = buytableDao.updateBuyTotalPrice(connection, cid);
        return buytableDao.updateCode(code,id,name);
    }

    @Override
    public boolean deleteByidBycid(Integer id,Integer cid) throws SQLException {
        Connection connection = null;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);

            boolean update = buytableDao.deleteCarPart(id,connection);
            boolean i = buytableDao.deleteBuyPart(cid,connection);
            if (update ==true && i ==true) {
                connection.commit();
                return true;
            }
            return false;
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public List<Producertable> listProducertable(Integer page, Integer limit) throws Exception {
        return buytableDao.listProducertable(page,limit);
    }

    @Override
    public long countProducertable() throws Exception {
        return buytableDao.countProducertable();
    }

    @Override
    public int addProducertable(Producertable producertable) throws Exception {
        return buytableDao.addProducertable(producertable);
    }

    @Override
    public int updateProducertable(Producertable producertable) throws Exception {
        return buytableDao.updateProducertable(producertable);
    }


    @Override
    public int deleteProducertable(Integer id) throws Exception {
        return buytableDao.deleteProducertable(id);
    }

    @Override
    public boolean updateUserTime(Integer id, int userId,String state) throws SQLException {
        Connection connection = null;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);

            boolean update = buytableDao.updateState(id,state,connection);
            int i = buytableDao.updateUserTime(id,userId,DateUtils.getNowTime(),connection);
            int i1 = buytableDao.updateBuyTotalPrice(connection, id);
            if (update == true && i > 0&&i1>0) {
                connection.commit();
                return true;
            }
            return false;
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public RespBean queryAllByState() {
        return RespBean.success(null,buytableDao.selectAll());
    }

    @Override
    public RespBean queryAllById(Integer id) {
        return RespBean.success(null,buytableDao.selectById(id));
    }
}